package sk.hackcraft.multibox.server;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import sk.hackcraft.multibox.util.IdentifiedCachedMap;

final public class Library {
	static public final IdentifiedCachedMap<Library> all = new IdentifiedCachedMap<Library>();
	
	final public File directory;
	private List<Library> libraries = null;
	private List<Song> songs = null;
	private boolean needRefresh = true;
	final public long id;
	final public String name;
	final public Library parent;
	
	public Library(File directory) {
		this(directory, null);
	}
	
	public Library(File directory, Library parent) {
		name = directory.getName();
		this.directory = directory;
		id = all.add(this);
		this.parent = parent;
	}
	
	public synchronized void parseSubStructure() {
		if(needRefresh) {		
			songs = new LinkedList<Song>();
			libraries = new LinkedList<Library>();
			
			for(File file : directory.listFiles()) {
				if(file.isDirectory()) {
					libraries.add(new Library(file, this));
				} else if(Song.isSong(file)) {
					songs.add(new Song(file));
				}
			}
		}
	}
	
	public void refresh() {
		needRefresh = true;
		parseSubStructure();
	}
	
	public synchronized List<Library> getLibraries() {
		if(needRefresh) {
			parseSubStructure();
		}
		return libraries;
	}
	
	public synchronized List<Song> getSongs() {
		return songs;
	}
	
	public JSONObject toJSON() {
		JSONObject object = new JSONObject();
		
		object.put("name", name);
		object.put("id", id);
		
		return object;
	}
}
